package org.flow.basic.threadpool;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author xl-9527
 * @since 2024/6/23
 **/
public class CustomThreadPoolDemo {

    private static final int CORE_NUM = 1; // Runtime.getRuntime().availableProcessors();

    public static void main(String[] args) {
        final CustomThreadPool customThreadPool = new CustomThreadPool(
                CORE_NUM, CORE_NUM,
                60, TimeUnit.SECONDS, new CustomRejectedExecutionHandler()
        );

        final CompletableFuture<Void> runAsync = CompletableFuture.runAsync(() -> {
            final Thread thread = Thread.currentThread();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("current thread name is => " + thread.getName());
        }, customThreadPool);
        final CompletableFuture<Void> runAsync2 = CompletableFuture.runAsync(() -> {
            final Thread thread = Thread.currentThread();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("current thread name is => " + thread.getName());
        }, customThreadPool);
        final CompletableFuture<Void> runAsync3 = CompletableFuture.runAsync(() -> {
            final Thread thread = Thread.currentThread();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("current thread name is => " + thread.getName());
        }, customThreadPool);

//        customThreadPool.execute(() -> {});

        CompletableFuture.allOf(runAsync, runAsync2, runAsync3).exceptionally(e -> {
            e.printStackTrace();
            return null;
        }).join();


        customThreadPool.shutdown();
    }
}
